package com.aichan.aibi.model.entity.login;

import com.alibaba.fastjson.annotation.JSONField;
import com.aichan.aibi.model.entity.Permission;
import com.aichan.aibi.model.entity.Role;
import com.aichan.aibi.model.entity.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mengyu
 * @date 2024/03/03 9:30
 * SpringSecurity UserDetails实现类
 */
@Data
public class LoginUser implements UserDetails {

    private User user;
    // 存储权限信息
    private List<Permission> permissions;
    // 存储角色信息
    private List<Role> roles;

    //存储SpringSecurity所需要的权限信息的集合
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        //把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities
        authorities = permissions.stream().map(Permission::getPermissionName).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        authorities.addAll(roles.stream().map(r -> "ROLE_" + r.getRoleName()).map(SimpleGrantedAuthority::new).toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getUserPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
